package com.lw.leetcode.tree.a;

import com.lw.leetcode.tree.TreeNode;

/**
 * 606. 根据二叉树创建字符串
 *
 * @Author liw
 * @Date 2021/5/11 17:35
 * @Version 1.0
 */
public class Tree2str {

    public String tree2str(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        find(root, sb);
        return sb.toString();
    }

    private void find(TreeNode root, StringBuilder sb) {
        if (root == null) {
            return;
        }
        sb.append(root.val);
        if (root.left != null || root.right != null) {
            sb.append('(');
            find(root.left, sb);
            sb.append(')');
        }

        if (root.right != null) {
            sb.append('(');
            find(root.right, sb);
            sb.append(')');
        }
    }

}
